#!/usr/bin/env python3
"""
Qwen代理服务器 - 在Windows本地运行，转发请求到Linux服务器
安装依赖：pip install flask requests paramiko
"""

import json
import requests
from flask import Flask, request, jsonify
from flask_cors import CORS
import paramiko
import threading
import time
import logging

app = Flask(__name__)
CORS(app)

# 配置
REMOTE_HOST = "188.18.57.151"
REMOTE_PORT = 23333
SSH_USER = "root"
SSH_PASSWORD = "JYDadmin-12345"
LOCAL_PORT = 5001

# SSH隧道管理
ssh_client = None
tunnel = None

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def create_ssh_tunnel():
    """创建SSH隧道"""
    global ssh_client, tunnel
    try:
        ssh_client = paramiko.SSHClient()
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.connect(REMOTE_HOST, username=SSH_USER, password=SSH_PASSWORD)
        
        # 创建隧道
        transport = ssh_client.get_transport()
        tunnel = transport.open_channel(
            "direct-tcpip",
            ("localhost", REMOTE_PORT),
            ("localhost", 0)
        )
        logger.info("SSH隧道建立成功")
        return True
    except Exception as e:
        logger.error(f"建立SSH隧道失败: {e}")
        return False

@app.route('/v1/chat/completions', methods=['POST'])
def proxy_chat():
    """代理聊天请求"""
    try:
        # 获取请求数据
        data = request.get_json()
        
        # 转发到远程Qwen服务
        response = requests.post(
            f"http://{REMOTE_HOST}:{REMOTE_PORT}/v1/chat/completions",
            json=data,
            timeout=30
        )
        
        return jsonify(response.json())
    except requests.exceptions.RequestException as e:
        # 如果直接连接失败，尝试通过SSH
        logger.warning(f"直接连接失败，尝试SSH方式: {e}")
        
        try:
            # 使用paramiko执行远程命令
            if not ssh_client:
                create_ssh_tunnel()
            
            # 通过SSH执行curl命令
            curl_cmd = f"""curl -X POST http://localhost:{REMOTE_PORT}/v1/chat/completions \
                -H "Content-Type: application/json" \
                -d '{json.dumps(data)}'"""
            
            stdin, stdout, stderr = ssh_client.exec_command(curl_cmd)
            result = stdout.read().decode()
            
            return jsonify(json.loads(result))
        except Exception as e2:
            logger.error(f"SSH方式也失败: {e2}")
            return jsonify({
                "error": f"无法连接到Qwen服务: {str(e2)}"
            }), 500

@app.route('/health', methods=['GET'])
def health_check():
    """健康检查"""
    return jsonify({"status": "healthy", "service": "QwenProxy"})

if __name__ == '__main__':
    print(f"""
    ====================================
    Qwen代理服务器
    ====================================
    
    代理地址: http://localhost:{LOCAL_PORT}
    目标服务: {REMOTE_HOST}:{REMOTE_PORT}
    
    使用方法：
    1. 修改 appsettings.json:
       "BaseUrl": "http://localhost:{LOCAL_PORT}"
    
    2. 启动Agent服务:
       dotnet run
    
    ====================================
    """)
    
    # 尝试建立SSH连接
    create_ssh_tunnel()
    
    # 启动Flask服务
    app.run(host='0.0.0.0', port=LOCAL_PORT, debug=False)



















